/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 */
package com.flyox.game.militarychess.server.minaserver;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.security.GeneralSecurityException;

import org.apache.mina.common.DefaultIoFilterChainBuilder;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;
import org.apache.mina.filter.ssl.SslFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.flyox.game.militarychess.util.ssl.SslContextFactory;

public class MinaServer {
	private final Logger logger = LoggerFactory.getLogger(getClass());
	private int port = 8088;
	
	public MinaServer(int port){
		this.port=port;
	}
	
	public void start() {
		try {
			NioSocketAcceptor acceptor = new NioSocketAcceptor(2);
			DefaultIoFilterChainBuilder chain = acceptor.getFilterChain();
			
			//chain.addLast("mdc", new MdcInjectionFilter());
			try {
				chain.addLast("sslFilter", new SslFilter(SslContextFactory.getInstance(true)));
			} catch (GeneralSecurityException e) {
				e.printStackTrace();
			}
			chain.addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));
			//chain.addLast("logger", new LoggingFilter());
			// Bind
			acceptor.setHandler(new MinaServerHandler());
			acceptor.bind(new InetSocketAddress(port));
			//acceptor.setReaderIdleTime(100);
		} catch (IOException e) {
			e.printStackTrace();
		}
		logger.trace("Listening on port " + port);
	}

}
